package com.example.chamberlainserver.security;

import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.TokenValidationService;
import com.example.chamberlainserver.Service.UserLogService;
import com.example.chamberlainserver.Service.UserService;
import com.example.chamberlainserver.mapper.UserLoginLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 自定义登出处理器
 * 在用户登出时记录登出日志
 */
@Component
public class LogoutFilter implements LogoutHandler {

    private final UserLogService userLogService;
    
    @Autowired
    private UserLoginLogMapper loginLogMapper;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TokenValidationService tokenValidationService;
    
    @Autowired
    public LogoutFilter(UserLogService userLogService) {
        this.userLogService = userLogService;
    }
    
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        // 获取请求头中的token并验证
        String requestTokenHeader = request.getHeader("Authorization");
        String jwtToken = tokenValidationService.extractTokenFromHeader(requestTokenHeader);

        try {
            if (jwtToken != null && tokenValidationService.isTokenNotExpired(jwtToken)) {
                // 从token中获取用户信息
                JwtTokenUtil.UserInfo userInfo = tokenValidationService.jwtTokenUtil.getUserInfoFromToken(jwtToken);
                String username = userInfo.getUsername();
                Integer userId = userInfo.getUserId();
                
                if (username != null && !username.isEmpty()) {
                    // 获取最近的登录日志ID
                    Long loginLogId = loginLogMapper.getLatestLoginLogIdByUsername(username);
                    
                    if (loginLogId != null) {
                        // 更新登出时间和会话时长
                        LocalDateTime logoutTime = LocalDateTime.now();
                        loginLogMapper.updateLogoutInfo(loginLogId, logoutTime);
                        
                        System.out.println("用户 " + username + " 登出成功，已更新登出时间");
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("更新登出时间失败: " + e.getMessage());
        }

        // 清除认证信息
        if (authentication != null) {
            SecurityContextHolder.clearContext();
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
    }
}